/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.auth.service.impl;

import com.xy.biz.auth.domain.bo.CaptchaBO;
import com.xy.biz.auth.manager.CaptchaManager;
import com.xy.biz.auth.service.CaptchaService;
import com.xy.lang.domain.Result;
import com.xy.tool.gid.service.GidService;
import com.xy.tool.profile.ProfileManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 *
 *
 * @author zsp
 * @date 2020-8-21
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

	@Autowired
	private CaptchaManager captchaManager;
	@Autowired
	private GidService gidService;
	@Autowired
	private ProfileManager profileManager;

	@Override
	public CaptchaBO saveCaptcha(String captchaCode, Integer type) {
		LocalDateTime now = LocalDateTime.now();
		CaptchaBO captchaBO = CaptchaBO.builder()
				.captchaId(gidService.generate())
				.captchaCode(captchaCode)
				.type(type)
				.expireTime(now.plusSeconds(60))
				.createTime(now)
				.build();
		captchaManager.saveCaptcha(captchaBO);
		return captchaBO;
	}

	@Override
	public Result<?> verifyCaptcha(Long captchaId, String captchaCode) {
		if(profileManager.isTendingToProd()) {
			if(null == captchaId || captchaId < 1L || !StringUtils.hasText(captchaCode)) {
				return Result.ofBadRequest("请先获取验证码");
			}
			CaptchaBO captchaBO = captchaManager.getCaptcha(captchaId);
			if (null == captchaBO) {
				return Result.ofBadRequest("请先获取验证码");
			}
			if (!(captchaBO.getCaptchaCode()).equalsIgnoreCase(captchaCode)) {
				return Result.ofBadRequest("输入了错误的验证码");
			}
			if (LocalDateTime.now().isAfter(captchaBO.getExpireTime())) {
				return Result.ofBadRequest("输入了失效的验证码");
			}
		}
		return Result.success();
	}

}
